<?php
/**
 * 用于表的拆分，按一个字段，将数据库的记录拆分成多个表。
 * 比如收藏表、文件上传表按照用户的编号来拆分记录
 * @author Arlon
 *
 */
class SplitModelBehavior extends ModelBehavior {
	
	public $name = 'SplitModel';
	
	public $split = 256;
	
	public function setup( Model $Model, $settings = array() ) {
		if( !is_array( $settings ) ) {
			$settings = array();
		}
		
		if( !is_array( $this->settings[$Model->alias] ) ) {
			$this->settings[$Model->alias] = array();
		}
		
		$this->settings[$Model->alias] = array_merge_recursive( $this->settings[$Model->alias], $settings );
	}
	// 设置必需callback，这样在之前会find一次，从而设置好了data_source的table表
// 	public function beforeDelete(Model $model, $cascade = true) {
// 	    return true;
// 	}
	
	public function beforeFind(Model $model, $query) {
		if(!empty($this->settings[$model->alias]['field'])) {
			$field = $this->settings[$model->alias]['field'];			
			if( $this->settings[$model->alias]['split'] ) {
				$this->split = $this->settings[$model->alias]['split'];
			}			
			if($query['conditions'][$field]) {
			    // 将分表的字段值传入模型中，内容存至oss的路径中包含了.如文章、帖子等
			    $model->{$field} = $query['conditions'][$field];	
			    
				$subfix = $query['conditions'][$field] % $this->split;
				$tablename = Inflector::tableize($model->alias).'_'.$subfix;
				$model->setSource($tablename);
			}
			elseif($query['conditions'][$model->alias.'.'.$field]) {
			    // 将分表的字段值传入模型中，内容存至oss的路径中包含了.如文章、帖子等
			    $model->{$field} = $query['conditions'][$model->alias.'.'.$field];
			    
				$subfix = $query['conditions'][$model->alias.'.'.$field] % $this->split;
				$tablename = Inflector::tableize($model->alias).'_'.$subfix;
				$model->setSource($tablename);
			}
			elseif($model->data[$model->alias][$field]){
				/* 修改this->exists的callback为before，save修改判断exists时会使用。*/
				$query['conditions'][$model->alias.'.'.$field] = $model->data[$model->alias][$field];
				$subfix = $model->data[$model->alias][$field] % $this->split;
				$tablename = Inflector::tableize($model->alias).'_'.$subfix;
				$model->setSource($tablename);

			}
			// else{
			// 	throw new Exception($model->alias." is Split Model need [$field] condition in find/update/delete", 1);
			// }
		}
		return $query;
	}
	
	public function beforeSave(Model $model) {
		if(!empty($this->settings[$model->alias]['field'])) {
			$field = $this->settings[$model->alias]['field'];
			if( $this->settings[$model->alias]['split'] ) {
				$this->split = $this->settings[$model->alias]['split'];
			}
			if($model->data[$model->alias][$field]) {
				$subfix = $model->data[$model->alias][$field] % $this->split;
				$tablename = Inflector::tableize($model->alias).'_'.$subfix;
				$model->setSource($tablename);
			}			
			// else{
			// 	throw new Exception($model->alias." is Split Model need [$field] condition in save", 1);
			// }
		}
	}
}